from flask import render_template, g, request, jsonify, session
from info import db, constants
from info.common import user_login_data
from info.models import User, Category, News
from info.modules.profile import profile_blu
from info.utils.image_storage import storage
from info.utils.response_code import RET


@profile_blu.route("/index")
@user_login_data
def index():
    data = {
        "user":g.user.to_dict()
    }
    return render_template("news/user.html", data=data)


@profile_blu.route("/user_info", methods=["post", "get"])
@user_login_data
def base_info():
    """
    修改基本资料(get:获取信息, post:修改信息)
    1.接受参数(用户名, 个性签名，性别)
    2.校验参数
    3.业务逻辑(更改数据库中的资料)
    4.返回响应
    :return:
    """
    if request.method == "GET":
        return render_template("news/user_base_info.html", data={"user":g.user.to_dict()})
    else:
        # 1.接受参数
        nick_name = request.json.get("nick_name")
        signature = request.json.get("signature")
        gender = request.json.get("gender")
        # 2.校验参数
        if not all(["nick_name", "signature", "gender"]):
            return jsonify(errno=RET.PARAMERR, errmsg='参数不足')
        if gender not in ("MAN", "WOMAN"):
            return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
        # 3.修改数据(更改数控中的数据)
        # 初始化模型
        user = g.user
        user.nick_name = nick_name
        user.signature = signature
        user.gender = gender
        try:

            db.session.commit()
        except Exception as f:
            print(f)
            db.session.rollback()
            return jsonify(errno=RET.DBERR, errmsg='数据保存失败')

        session["nick_name"] = nick_name

        data = {
            "user":user.to_dict()
        }
    return jsonify(errno=RET.OK, errmsg='更新成功', data=data)


@profile_blu.route("/pic_info", methods=["get", "post"])
@user_login_data
def pic_info():
    """
    七牛云上传头像
    1.获取参数(头像的二进制文本信息)
    2.检验参数
    3.上传到七牛云上
    4.保存url到数据库中
    5.返回拼接头像url
    :return:
    """
    if request.method == "GET":
        return render_template("news/user_pic_info.html", data={"user":g.user.to_dict()})
    else:
        # 1.获取参数(头像的二进制avatar)
        try:
            avatar = request.files.get("avatar").read()
        except Exception as f:
            return jsonify(errno=RET.PARAMERR, errmsg="读取文件出错")
        # 将头像上传到七牛云上
        url = storage(avatar)
        # 保存到数据库中
        user = g.user
        user.avatar_url = url
        try:
            db.session.commit()
        except Exception as f:
            return jsonify(errno=RET.DATAERR, errmsg="数据库保存失败")
        return jsonify(errno=RET.OK, errmsg="保存成功",data={"avatar_url": constants.QINIU_DOMIN_PREFIX + url})


@profile_blu.route("/collection")
@user_login_data
def user_collection():
    """
    用户收藏:获取页数
    数据库分页查询
    返回数据
    :return:
    """
    page = request.args.get("p", 1)

    try:
        page = int(page)
    except Exception as f:
        print(f)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    # 从数据库中查找所有的收藏，以分页返回
    user = g.user
    current_page = 1
    total_page = 1
    try:
        paginate = user.collection_news.paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        # 当前的页数
        current_page = paginate.page
        # 总页数
        total_page = paginate.pages
        # 分页的信息
        collections = paginate.items
    except Exception as f:
        print(f)
    collection_list = []
    for collection in collections:
        collection_list.append(collection.to_basic_dict())
    data = {"total_page": total_page,
            "current_page": current_page, "collections": collection_list}
    return render_template("news/user_collection.html", data=data)


@profile_blu.route("/news_release", methods=["get", "post"])
@user_login_data
def news_release():
    """
    1.移除最新类
    2.获取参数()
    :return:
    """
    if request.method == "GET":
        try:
            categorys = Category.query.all()
        except Exception as f:
            print(f)
            return jsonify(errno=RET.DBERR, errmsg='数据库查找失败')
        # 移除最新类
        category_list = list()
        if not categorys:
            return jsonify(errno=RET.DBERR, errmsg='查找失败')
        for category in categorys:
            category_list.append(category.to_dict())
        category_list.pop(0)
        return render_template("news/user_news_release.html", data = {"category_list":category_list})

    # 获取参数
    source = "个人发布"
    title = request.form.get("title")
    category_id = request.form.get("category_id")
    digest = request.form.get("digest")
    content = request.form.get("content")
    index_image = request.files.get("index_image")
    if not all([title, category_id, digest, index_image, content]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")
    try:
        category_id = int(category_id)
    except Exception as f:
        print(f)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    # 读取index_image
    try:
        iamge = index_image.read()
    except Exception as f:
        print(f)
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
    # 将图片保存到七牛云上
    try:
        key = storage(iamge)
    except Exception as f:
        print(f)
        return jsonify(errno=RET.THIRDERR, errmsg="上传图片错误")
    # 保存到数据库中
    # 初始化新闻模型
    news = News()
    news.title = title
    news.digest = digest
    news.source = source
    news.content = content
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
    news.category_id = category_id
    news.user_id = g.user.id
    # 1代表待审核状态
    news.status = 1
    # 添加到数据库中
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")
    # 5. 返回结果
    return jsonify(errno=RET.OK, errmsg="发布成功，等待审核")


@profile_blu.route("/news_list")
@user_login_data
def news_list():
    """
    分页查询用户发布的新闻
    :return:
    """
    # 根据用户查询到发布的新闻
    page = request.args.get("p", 1)
    try:
        page = int(page)
    except Exception as f:
        print(f)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    news_li = []
    current_page = 1
    total_page = 1
    try:
        news_dict_list = News.query.filter(News.user_id == g.user.id).paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        news_li = news_dict_list.items
        # 获取当前页
        current_page = news_dict_list.page
        # 获取总页数
        total_page = news_dict_list.pages
    except Exception as f:
        print(f)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")
    if not news_dict_list:
        return jsonify(errno=RET.DBERR, errmsg="为查询到数据")
    news_dict_li = []
    for news in news_li:
        news_dict_li.append(news.to_review_dict())
    data = {"news_list": news_dict_li, "total_page": total_page, "current_page": current_page}
    return render_template("news/user_news_list.html", data=data)